<template>
  <div class="app-container">
    <el-row :gutter="18">
      <el-col :span="16">
        <el-descriptions
          :title="filterOrderStatus(orderInfo ? orderInfo.orderStatus : '')"
          :column="1"
          class="out-border mb10"
        >
          <!-- 已下单待支付 -->
          <template
            slot="extra"
            v-if="orderInfo && orderInfo.orderStatus == 'WAIT_PAY'"
          >
            <div style="display: flex; justify-content: flex-end">
              <el-button size="small" type="primary" @click="onGoPay"
                >去支付</el-button
              >
              <el-button size="small" type="danger" @click="onCancelOrder"
                >取消订单</el-button
              >
            </div>
            <div class="tip mt10" style="color: red">
              待支付金额：{{
                orderInfo &&
                Number(orderInfo.payAmount || 0).tranFormat(2, -2, false)
              }}元，请在下单30分钟内完成给支付，剩余时间：
              <el-statistic
                ref="statistic"
                @finish="hilarity"
                format="mm:ss"
                :value="deadline"
                :time-indices="deadline >= 0"
              >
              </el-statistic>
            </div>
          </template>
          <!-- 已支付待派单 -->
          <template
            slot="extra"
            v-if="orderInfo && orderInfo.orderStatus == 'WART_SEND'"
          >
            <div style="display: flex; justify-content: flex-end">
              <el-button
                size="small"
                type="primary"
                @click="openSendOrderDialog"
                >派单</el-button
              >
              <el-button size="small" type="danger" @click="onRefundClose"
                >退款关闭</el-button
              >
            </div>
          </template>
          <!-- 已派单待预约 / 已预约，待上门 -->
          <template
            slot="extra"
            v-if="
              orderInfo &&
              ['WART_APPOINTMENT', 'WART_SITE', 'WORKING'].includes(
                orderInfo.orderStatus
              )
            "
          >
            <div style="display: flex; justify-content: flex-end">
              <el-button size="small" type="success" @click="onAddPrice"
                >加价</el-button
              >
              <el-button
                size="small"
                type="primary"
                @click="openSendOrderDialog"
                >改派</el-button
              >
              <el-button size="small" type="danger" @click="onRefundClose"
                >退款关闭</el-button
              >
            </div>
            <div
              v-if="orderInfo && orderInfo.extraServiceOrderId"
              style="display: flex; justify-content: flex-end; margin-top: 10px"
            >
              <el-button size="small" type="success" @click="onPayAddPrice"
                >去支付</el-button
              >
              <el-button size="small" type="primary" @click="onCloseAddPrice"
                >关闭加价单</el-button
              >
            </div>
            <div
              style="color: red; font-size: 12px; padding-left: 40px"
              v-if="orderInfo && orderInfo.extraOrderAmount"
            >
              {{
                orderInfo && orderInfo.extraOrderAmount | filterPriceFormat
              }}元加价单待支付
            </div>
          </template>
          <!-- 已完工，待验收 -->
          <template
            slot="extra"
            v-if="orderInfo && orderInfo.orderStatus == 'WART_CHECK'"
          >
            <div style="display: flex; justify-content: flex-end">
              <!-- 商家端有 -->
              <el-button size="small" type="success" @click="handleOrderFinish"
                >验收完成</el-button
              >
              <!-- 商家端有 -->
              <el-button size="small" type="warning" @click="onSellAfterDialog"
                >发起售后</el-button
              >
            </div>
          </template>
          <!-- 已验收，订单完成 -->
          <template
            slot="extra"
            v-if="orderInfo && orderInfo.orderStatus == 'FINISH'"
          >
            <div style="display: flex; justify-content: flex-end">
              <!-- 商家端有 -->
              <el-button size="small" type="success" @click="onRateDialog"
                >服务评价</el-button
              >
              <!-- 商家端有 -->

              <el-button size="small" type="warning" @click="onSellAfterDialog"
                >发起售后</el-button
              >
            </div>
            <div>订单完结15天内可发起售后</div>
          </template>
          <el-descriptions-item label="订单号">
            {{ orderInfo && orderInfo.serviceOrderId }}
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">
            {{ orderInfo && orderInfo.createTime }}
          </el-descriptions-item>
        </el-descriptions>
        <el-tabs type="border-card">
          <el-tab-pane label="订单信息">
            <OrderInfo :orderInfo="orderInfo" />
          </el-tab-pane>
          <el-tab-pane label="异常信息">暂无</el-tab-pane>
          <el-tab-pane label="服务评价">
            <div v-if="orderInfo && orderInfo.evaluateResDTO">
              <el-descriptions :column="1">
                <el-descriptions-item label="六鸽服务打分">
                  <el-rate :value="orderInfo.evaluateResDTO.mark"></el-rate>
                </el-descriptions-item>
                <el-descriptions-item label="标签">
                  <el-tag
                    :key="tag"
                    v-for="tag in orderInfo.evaluateResDTO.labels.split(',')"
                    style="margin: 0 5px 5px 0"
                  >
                    {{ tag }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="描述"
                  >{{ orderInfo.evaluateResDTO.describe }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <div>暂无</div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="8">
        <el-descriptions
          title="师傅信息"
          :column="1"
          class="out-border mb10"
          :colon="false"
        >
          <!-- 已下单待支付 -->
          <el-descriptions-item v-if="orderInfo && orderInfo.workerName">
            <el-row class="row">
              <el-col :span="6">
                <el-avatar
                  class="avatar"
                  :src="orderInfo.workerAvatar"
                ></el-avatar>
              </el-col>
              <el-col :span="18">
                <div class="item">姓名:{{ orderInfo.workerName }}</div>
                <div class="item">手机号:{{ orderInfo.workerMobile }}</div>
                <div class="item">师傅id:{{ orderInfo.workerId }}</div>
              </el-col>
              <el-col :span="24" style="margin-top: 20px">
                <el-timeline>
                  <el-timeline-item
                    v-if="orderInfo.payTime"
                    :timestamp="orderInfo.receiveOrderTime"
                  >
                    支付完成，师傅接到订单
                  </el-timeline-item>
                  <el-timeline-item
                    v-if="orderInfo.appointmentDate"
                    :timestamp="`${orderInfo.appointmentDate} ${orderInfo.appointmentStartTime}-${orderInfo.appointmentFinishTime}`"
                  >
                    师傅预约上门时间
                  </el-timeline-item>
                  <el-timeline-item
                    v-for="item in orderInfo.orderChangeResDTOList"
                    :key="item.createTime"
                    :timestamp="
                      item.changeType === 'UPDATE_APPOINTMENT'
                        ? `${item.appointmentDate} ${item.appointmentStartTime}-${item.appointmentFinishTime}`
                        : item.createTime
                    "
                  >
                    {{ item.changeType | filterChangeTypeEnum }}
                  </el-timeline-item>
                </el-timeline>
              </el-col>
            </el-row>
          </el-descriptions-item>
          <el-descriptions-item v-else>暂无</el-descriptions-item>
          <!-- 已下单待支付 -->
        </el-descriptions>
      </el-col>
    </el-row>
    <ThePay ref="payRefs" />
    <SendOrder
      v-if="orderInfo && orderInfo.serviceOrderId"
      ref="sendOrderRefs"
      :serviceOrderId="orderInfo.serviceOrderId"
      @sendOrder="handleSendOrder"
      @synchronous="handleSynchronous"
    />
    <AddPrice
      ref="addPriceRefs"
      :orderInfo="orderInfo"
      @addPrice="handleAddPrice"
    />
    <RefundClose
      ref="refundCloseRefs"
      :orderInfo="orderInfo"
      @refundClose="handleRefundClose"
    />
    <SellAfter
      ref="sellAfterRefs"
      :serviceOrderId="serviceOrderId"
      @sendSellAfter="handleSellAfter"
    />
    <TheRate ref="rateRefs" @onRate="handleRate" />
  </div>
</template>

<script>
import {
  apiOrderBDetail,
  apiOrderBCancelOrder,
  apiOrderBSendOrder,
  apiOrderBRefundClose,
  apiExtraServiceOrderBCloseRaise,
  apiOrderBEvaluate,
  apiExtraServiceOrderCreate,
  apiOrderBSynchronous,
  apiOrderBFinish,
} from "@/api/order.js";
import { apiOrderBApplyRefund } from "@/api/salesAfter.js";

import { filterOrderStatus, filterChangeTypeEnum } from "@/filters/index";
import OrderInfo from "./components/orderInfo.vue";
import SendOrder from "./components/sendOrder.vue";
import AddPrice from "./components/addPrice.vue";
import ThePay from "@/components/ThePay/index.vue";
import RefundClose from "./components/refundClose.vue";
import SellAfter from "./components/sellAfter.vue";
import TheRate from "@/components/TheRateDialog/index.vue";

export default {
  components: {
    SellAfter,
    OrderInfo,
    ThePay,
    SendOrder,
    AddPrice,
    RefundClose,
    TheRate,
  },
  data() {
    return {
      serviceOrderId: "",
      orderInfo: null,
      deadline: 0,
      filterOrderStatus: filterOrderStatus,
      filterChangeTypeEnum: filterChangeTypeEnum,
    };
  },
  mounted() {
    try {
      const { serviceOrderId } = this.$route.query;
      this.serviceOrderId = serviceOrderId;
      this.getData();
    } catch (error) {
      this.$message("丢失主键");
    }
  },
  methods: {
    getData() {
      apiOrderBDetail({ serviceOrderId: this.serviceOrderId }).then((res) => {
        if (res.code == "SUCCESS") {
          this.orderInfo = res.data;
          const downTime =
            new Date(res.data.createTime).getTime() +
            30 * 60 * 60 * 1000 -
            Date.now();
          this.deadline = downTime > 0 ? downTime : 0;
        }
      });
    },

    // 支付
    onGoPay() {
      // 显示支付
      const payUtils = {
        payWay: "BALANCE",
        payAmount: this.orderInfo.payAmount,
        ext: {
          tradeType: "NATIVE",
          serviceOrderId: this.orderInfo.serviceOrderId,
        },
      };
      this.$refs.payRefs.onShow(payUtils);
    },
    // 取消订单
    onCancelOrder() {
      this.$confirm("平台正在安排合适的师傅！", "确定取消订单？", {
        confirmButtonText: "取消订单",
        cancelButtonText: "返回",
        type: "warning",
      })
        .then(() => {
          apiOrderBCancelOrder({ serviceOrderId: this.serviceOrderId }).then(
            (res) => {
              if (res.code == "SUCCESS") {
                this.$message({
                  type: "success",
                  message: "取消订单成功!",
                });
                this.getData();
              }
            }
          );
        })
        .catch(() => {});
    },
    // 打开选择派单师傅弹窗
    openSendOrderDialog() {
      this.$refs.sendOrderRefs.onShow();
    },
    // 确定派单选择师傅
    handleSendOrder(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: "确定派给师傅？",
        message: h("div", null, [
          h("p", null, `师傅姓名：${row.workerName}`),
          h("p", null, `手机号：${row.userPhoneNumber}`),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定派单",
        cancelButtonText: "取消",
      }).then((action) => {
        console.log(action, "action");
        apiOrderBSendOrder({
          serviceOrderId: this.serviceOrderId,
          workerId: row.workerId,
        }).then((res) => {
          if (res.code == "SUCCESS") {
            this.$refs.sendOrderRefs.onClose();
            this.$message({
              type: "success",
              message: "派单成功!",
            });
            this.getData();
          }
        });
      });
    },
    // 退款关闭
    onRefundClose() {
      const { orderStatus, serviceOrderId } = this.orderInfo;
      if (orderStatus == "WART_SEND") {
        this.$confirm("支付款原路返回", "确定退款关闭订单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            apiOrderBRefundClose({
              serviceOrderId,
            }).then((res) => {
              if (res.code === "SUCCESS") {
                this.$message({ type: "success", message: "退款关闭成功" });
                this.getData();
              }
            });
          })
          .catch(() => {});
      } else if (orderStatus == "WART_APPOINTMENT") {
        this.$refs.refundCloseRefs.onShow();
      }
    },
    // 确认关闭退款单
    handleRefundClose(row) {
      console.log(row);
      apiOrderBRefundClose({
        serviceOrderId: this.orderInfo.serviceOrderId,
        ...row,
      }).then((res) => {
        if (res.code === "SUCCESS") {
          this.$message({ type: "success", message: "退款关闭成功" });
          this.getData();
        }
      });
    },
    // 确认同步服务商
    handleSynchronous(row) {
      this.$confirm(
        `后续订单由服务商“${row.saasName}”进行履约处理`,
        "确定订单同步给服务商?",
        {
          confirmButtonText: "确定同步",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          apiOrderBSynchronous({ serviceOrderId: this.serviceOrderId }).then(
            (res) => {
              if (res.code === "SUCCESS") {
                this.$message({ type: "success", message: "同步成功" });
                this.getData();
              } else {
                this.$alert("服务商未开通此区域", "同步失败", {
                  confirmButtonText: "确定",
                  callback: (action) => {},
                });
              }
            }
          );
        })
        .catch(() => {});
    },
    // 加价弹窗
    onAddPrice() {
      this.$refs.addPriceRefs.onShow("weChat");
    },
    // 确认加价，并支付
    handleAddPrice(values) {
      console.log(this.orderInfo);
      apiExtraServiceOrderCreate({
        ...values,
        commissionAmount: values.commissionAmount * 100,
        saasAmount: values.saasAmount * 100,
        serviceOrderId: this.orderInfo.serviceOrderId,
      }).then((res) => {
        this.$message({ type: "success", message: "创建加价单成功" });
        const payUtils = {
          payWay: "BALANCE",
          payAmount: res.data.saasAmount + res.data.commissionAmount,
          mode: "extraOrder",
          ext: {
            tradeType: "NATIVE",
            extraServiceOrderId: res.data.extraServiceOrderId,
          },
        };
        this.$refs.payRefs.onShow(payUtils);
      });
    },
    // 支付加价单
    onPayAddPrice() {
      const payUtils = {
        payWay: "BALANCE",
        payAmount: this.orderInfo.extraOrderAmount,
        mode: "extraOrder",
        ext: {
          tradeType: "NATIVE",
          extraServiceOrderId: this.orderInfo.extraServiceOrderId,
        },
      };
      this.$refs.payRefs.onShow(payUtils);
    },
    // 关闭加价单
    onCloseAddPrice() {
      apiExtraServiceOrderBCloseRaise({
        extraServiceOrderId: this.orderInfo.extraServiceOrderId,
      }).then((res) => {
        if (res.code === "SUCCESS") {
          this.$message({ type: "success", message: "关闭加价单成功" });
          this.getData();
        }
      });
    },
    // 发起售后弹窗
    onSellAfterDialog() {
      this.$refs.sellAfterRefs.onShow();
    },
    handleSellAfter(values) {
      const params = {
        serviceOrderId: this.serviceOrderId,
        afterSaleType: values.afterSaleType, //售后类型
        problem: values.problem, //问题描述
        phone: values.phone, //联系电话
        proof: values.proof.join(","), //证据信息
      };
      apiOrderBApplyRefund({ ...params }).then((res) => {
        if (res.code === "SUCCESS") {
          this.$message({ type: "success", message: "发起售后成功" });
          this.getData();
        }
      });
    },
    // 订单验收完成
    handleOrderFinish() {
      this.$confirm("确认验收无误?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          apiOrderBFinish({
            serviceOrderId: this.orderInfo.serviceOrderId,
          }).then((res) => {
            this.$message({ type: "success", message: "订单验收完成" });
            this.getData();
          });
        })
        .catch(() => {});
    },
    onRateDialog() {
      this.$refs.rateRefs.onShow();
    },
    handleRate(e) {
      const { remark, rate, tags } = e;
      const params = {
        serviceOrderId: this.orderInfo.serviceOrderId,
        describe: rate,
        mark: remark,
        labels: tags.join(","),
      };
      apiOrderBEvaluate({ ...params }).then((res) => {
        if (res.code === "SUCCESS") {
          this.$message({ type: "success", message: "服务评分成功" });
          this.getData();
        }
      });
    },
    // 支付倒计时结束
    hilarity() {
      this.deadline > 0 && this.getData();
    },
  },
};
</script>
<style scoped lang="scss">
.tip {
  display: flex;
  ::v-deep .el-statistic {
    width: auto;
    display: inline-block;
    .con {
      color: red !important;
      .number {
        font-size: 16px !important;
        line-height: auto;
      }
    }
  }
}
.row {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .avatar {
    width: 80px;
    height: 80px;
  }
}
</style>
